package com.hzw.net.utils.recyclerview

import android.graphics.Canvas
import android.graphics.Path
import android.graphics.Rect
import android.graphics.RectF
import android.view.View
import android.view.ViewTreeObserver
import androidx.recyclerview.widget.RecyclerView
import com.hzw.core.log.logE
import com.hzw.core.log.logW

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/8/24 10:57
 *
 * @Description:
 *
 */
class CornerRadiusItemDecoration(
    recyclerView: RecyclerView,
    val topLeftRadius: Float = 0f,
    val topRightRadius: Float = 0f,
    val bottomLeftRadius: Float = 0f,
    val bottomRightRadius: Float = 0f
) : RecyclerView.ItemDecoration() {

    var lastItemView: View? = null
    private var recyclerViewBottom = -1

    val rectF = RectF()
    val path = Path()
    val radii = arrayOf(
        topLeftRadius, topLeftRadius,
        topRightRadius, topRightRadius,
        bottomLeftRadius, bottomLeftRadius,
        bottomRightRadius, bottomRightRadius
    ).toFloatArray()

    init {
        recyclerView.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                recyclerView.viewTreeObserver.removeOnGlobalLayoutListener(this)
                rectF.set(
                    0f,
                    0f,
                    recyclerView.measuredWidth.toFloat(),
                    recyclerView.measuredHeight.toFloat()
                )

                path.reset()
                path.addRoundRect(rectF, radii, Path.Direction.CCW)

                "recycler宽高 = ${rectF.toShortString()}".logW()
                radii.contentToString().logE()
            }
        })
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)

        lastItemView =
            if (parent.getChildAdapterPosition(view) == parent.adapter?.itemCount ?: 0 - 1) {
                view
            } else {
                null
            }
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        rectF.set(
            0f,
            0f,
            parent.measuredWidth.toFloat(),
            parent.measuredHeight.toFloat()
        )
        if (lastItemView != null) {
            val bottom = parent.layoutManager?.getBottomDecorationHeight(lastItemView!!) ?: 0
            recyclerViewBottom = lastItemView!!.bottom + bottom

            if (rectF.bottom > recyclerViewBottom) {
                rectF.bottom = recyclerViewBottom.toFloat()
            }
        }
        c.clipRect(rectF)
        c.clipPath(path)
    }
}